package cn.rose.thread;

import java.util.LinkedList;

/**
 * @FileName ThreadPool.java
 * @Description: 
 * @author rose
 * @version 1.0
 * <p>Company: ROSE-SOFT</p>
 * <p>Copyright: Copyright (c) 2011</p>
 */
public class ThreadPool {
	private final LinkedList<Runnable> queue;
	private final int intThreads;
	private final PoolWork[] poolWorks;
	public ThreadPool(int n){
		queue = new LinkedList<Runnable>();
		intThreads = n;
		poolWorks = new PoolWork[intThreads];
		for (int i = 0; i < intThreads; i++) {
			poolWorks[i] = new PoolWork();
			poolWorks[i].start();
			System.out.println(i);
		}
	}
	
	public void execute(Runnable r) {
		synchronized (queue) {
			queue.add(r);
			queue.notify();
		}
	}
	
	
	private class PoolWork extends Thread {
		@Override
		public void run() {
			
			Runnable r = null;
			
			while(true){
				synchronized (queue) {
					while(queue.isEmpty()) {
						try {
							queue.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					r = queue.removeFirst();
				}
				try {
					r.run();//开始执行线程
				} catch (Exception e) {
					//TODO log
				}
			}
			
			
		}
	}
}
